import '../asset/style/style.scss';
import Header from './header';
import * as Util from './util';
import { createGetAPI } from './fetch';

class Page {
  [key: string]: any;
  constructor() {
    this.categoryId = Util.getParam('categoryId');
    this.page = Util.getParam('page');
    this.id = Util.getParam('id');
    this.header = new Header();
    this.$body = $(".module-body");

    this.buildBread();
    this.loadFromServer();
  }

  loadFromServer() {
    const api = createGetAPI(`bus/article/articleDetail.htm`, { id: this.id });
    const result = api();
    result.then((result) => {
      if (result.body) {
        this.renderTitle(result.body.name);
        this.render(result.body);
      }
    }).catch((error) => {
      console.log(error);
      this.error();
    });
  }

  renderTitle(name) {
    $(".header-mini-text").text(name);
    $("title").text('未来守护--' + name);
  }

  render(data) {
    const html = [];
    html.push(`<div class="article-title ellipsis2">${data.name}</div>`);
    html.push(`<div class="article-author">`);
    html.push(` <div class="article-author-name">作者：${data.authorName}</div>`);
    html.push(` <div class="article-author-time">发布时间：${Util.formatDate(data.publishTime, 'YYYY-MM-dd')}</div>`);
    html.push(`</div>`);
    if (data.paragraphs && data.paragraphs.length > 0) {
      data.paragraphs.forEach(item => {
        if (item.type === "01") {
          html.push(`<div class="article-paragraph">`);
          html.push(item.content);
          html.push(`</div>`);
        } else {
          console.log('商品未能显示。。。')
        }
      })
    } else {
      html.push(`<div>`);
      html.push(`<br/>`);
      html.push(`<br/>`);
      html.push(`<br/>`);
      html.push(`<center>没有内容！</center>`);
      html.push(`<br/>`);
      html.push(`<br/>`);
      html.push(`<br/>`);
      html.push(`</div>`);
    }
    const $content = $(html.join(''));
    this.autoImage($content);
    this.$body.empty().append($content);
  }

  error() {
    const html = [];
    html.push(`<div>`);
    html.push(`<br/>`);
    html.push(`<br/>`);
    html.push(`<br/>`);
    html.push(`<center>加载失败，点击重试！</center>`);
    html.push(`<br/>`);
    html.push(`<br/>`);
    html.push(`<br/>`);
    html.push(`</div>`);
    const $error = $(html.join(''));
    $error.on('click', () => {
      $error.off('click');
      this.loadFromServer();
    })
    this.$body.html($error);
  }

  buildBread() {
    const html = [];
    html.push(`<a class="bread-item--line">\\</a>`);
    if (this.categoryId === '1') {
      html.push(`<a href="page1.html?page=${this.page}" class="bread-item">`);
      html.push(`什么是侧弯`);
      html.push(`</a>`);
    } else if (this.categoryId === '2') {
      html.push(`<a href="page1.html?page=${this.page}" class="bread-item">`);
      html.push(`体操矫形`);
      html.push(`</a>`);
    } else if (this.categoryId === '3') {
      html.push(`<a href="page1.html?page=${this.page}" class="bread-item">`);
      html.push(`支具矫形`);
    } else if (this.categoryId === '4') {
      html.push(`<a href="page1.html?page=${this.page}" class="bread-item">`);
      html.push(`手术矫形`);
      html.push(`</a>`);
    }
    $(".bread").append(html.join(''));
  }
  autoImage($parent) {
    const _this = this;
    const $imgs = $("img", $parent);
    $imgs.each(function () {
      const $img = $(this);
      const src = $img.attr('src');
      $img.removeAttr('src');
      const attr = {
        'onload': this.onImageSuccess,
        'onerror': this.onImgError,
        'data-src': $img.attr('src'),
        //'src': 'image/default.jpeg',
      };
      $img.attr(attr).addClass('lazy-image');

      var img = new Image();
      img.onload = function () {
        $img.attr("src", src);
        _this.onImageSuccess($img, img);
      };
      img.onerror = function () {
        _this.onImgError($img);
      };
      img.src = src;
    });
  }
  onImgError($img) {
    if (!$img.hasClass('error-image')) {
      $img.attr('src', 'image/default.jpeg').addClass('error-image article-auto-image');
    }
  }

  onImageSuccess($img, img) {
    // const img = this;
    // const $img = $(img);
    const W = $(window).width()
    let width = $img.attr("width");
    const _width_ = $img.attr("data-width");
    if (_width_) {
      width = _width_;
    } else {
      $img.attr("data-width", width);
    }
    if (!width) {
      width = img.width;
      if (width >= W - 32) {
        $img.addClass('article-auto-image');
      }
    } else if (width.indexOf("%") < 0) {
      if (Number.parseInt(width) >= W - 32) {
        $img.addClass('article-auto-image');
      }
    }
  }
}

$(() => {
  new Page();
});